<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Model;

use Hyperf\DbConnection\Model\Model as BaseModel;
use Carbon\Carbon;

abstract class Model extends BaseModel
{
    // 兼容tp6字段
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';
    const DELETED_AT = 'delete_time';
    public function fromDateTime($value) {
        if (empty($value)) return null;
        return strval($value->timestamp);
    }
    protected $dateFormat = 'Y-m-d H:i:s';
    // protected $dateFormat = 'c'; // 兼容iOS下原生js的Date()
    
    /**
     * 传入id进行更新，不传id则新建
     */
    public static function upsert(array $data) : Model {
        if (!empty($data['id'])) {
            $model = self::find($data['id']);
            if ($model == null) throw new \Exception('找不到id');
            $model->fill($data); // 根据子类具体模型的$fillable过滤
            $model->save();
        }else{
            $model = self::create($data);
        }
        return $model;
    }
}
